//api

(function ($) {
    $.extend({
        panTo: function (point) {
            var mk = new BMap.Marker(point);
            map.addOverlay(mk);
            map.panTo(point);
            setPointSpan(point);
        },
        panStrTo: function (strPoint) {
            let pointList = strPoint.split(',');
            let point = {
                lng: pointList[0],
                lat: pointList[1]
            }
            var mk = new BMap.Marker(point);
            map.addOverlay(mk);
            map.panTo(point);
            // setPointSpan(point);
        }

    })
})(jQuery);
var selectPoint = $("#coordinates input").val();

// 百度地图API功能
function G(id) {
    return document.getElementById(id);
}

var map = new BMap.Map("allmap");
//初始化经纬度不为空 跳转到这个地址
var regx = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)+,(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)+$/;
var re = new RegExp(regx);

// map.centerAndZoom("北京", 13); // 初始化地图,设置城市和地图级别。

if (re.test(selectPoint)) {
    //定位
    var sit = selectPoint.split(",")
    var new_point = new BMap.Point(sit[0], sit[1]);
    map.centerAndZoom(new_point, 18);
    var mr = new BMap.Marker(new_point);
    map.addOverlay(mr);
    // map.panTo(new_point);
    setPointSpan(new_point)
} else {
    map.centerAndZoom("北京", 13); // 初始化地图,设置城市和地图级别。
//浏览器定位
    //判断之前是否定位过；
    var sessionPoint = sessionStorage.getItem("point");
    console.log(selectPoint)
    if (re.test(sessionPoint)) {
        // $.panStrTo(sessionPoint);
    } else {
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                // var mk = new BMap.Marker(r.point);
                // map.addOverlay(mk);
                // map.centerAndZoom(r.point, 15); // 初始化地图,设置城市和地图级别。
                map.panTo(r.point);
                console.log("保存定位：", r.point)
                sessionStorage.setItem("point", r.point.lng + ',' + r.point.lat)
            } else {
                // layer.msg('failed' + this.getStatus());
                layer.msg('定位失败');
            }
        }, {enableHighAccuracy: true})
    }
}

//添加控件和比例尺
var top_right_navigation = new BMap.NavigationControl({
    anchor: BMAP_ANCHOR_TOP_RIGHT,
    type: BMAP_NAVIGATION_CONTROL_SMALL
}); //右上角，仅包含平移和缩放按钮
map.addControl(top_right_navigation);

/*缩放控件type有四种类型:
BMAP_NAVIGATION_CONTROL_SMALL：仅包含平移和缩放按钮；BMAP_NAVIGATION_CONTROL_PAN:仅包含平移按钮；BMAP_NAVIGATION_CONTROL_ZOOM：仅包含缩放按钮*/

//坐标输入框赋值
function setPoint(point) {
    $("#coordinates input").val(point.lng + "," + point.lat)
}

function setPointSpan(point) {
    var geoc = new BMap.Geocoder();
    geoc.getLocation(point, function (rs) {
        console.log(rs)
        console.log(rs.address)
        $("#coordinates span i").html("  " + rs.address + (rs.surroundingPois[0] != null ? rs.surroundingPois[0].title : ""));
    })
}

//右击菜单
var menu = new BMap.ContextMenu();
var txtMenuItem = [
    {
        text: '设置位置',
        callback: function (c) {
            setPoint(c);
            setPointSpan(c);
        }
    }
];
for (var i = 0; i < txtMenuItem.length; i++) {
    menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
}
map.addContextMenu(menu);

//单击获取点击的经纬度
// map.addEventListener("click", function (e) {
//     alert(e.point.lng + "," + e.point.lat);
// });

// 定义一个控件类,即function
function ZoomControl() {
    this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
    this.defaultOffset = new BMap.Size(10, 10);
}

// 通过JavaScript的prototype属性继承于BMap.Control
ZoomControl.prototype = new BMap.Control();

// 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
// 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
ZoomControl.prototype.initialize = function (map) {
    // 创建一个DOM元素
    var div = document.createElement("div");
    div.innerHTML = '<div id="r-result" style="font-size: 20px;">搜索：<input type="text" id="suggestId" size="20" value="百度" style="width:200px;" /></div><div id="searchResultPanel" style="border:1px solid #C0C0C0;width:200px;height:auto; display:none;"></div>';

    // 添加DOM元素到地图中
    map.getContainer().appendChild(div);
    // 将DOM元素返回
    return div;
}

// 创建控件
var myZoomCtrl = new ZoomControl();
// 添加到地图当中
map.addControl(myZoomCtrl);

var ac = new BMap.Autocomplete( //建立一个自动完成的对象
    {
        "input": "suggestId"
        , "location": map
    });
ac.addEventListener("onhighlight", function (e) { //鼠标放在下拉列表上的事件
    var str = "";
    var _value = e.fromitem.value;
    var value = "";
    if (e.fromitem.index > -1) {
        value = _value.province + _value.city + _value.district + _value.street + _value.business;
    }
    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
    value = "";
    if (e.toitem.index > -1) {
        _value = e.toitem.value;
        value = _value.province + _value.city + _value.district + _value.street + _value.business;
    }
    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
    G("searchResultPanel").innerHTML = str;
});

var myValue;
ac.addEventListener("onconfirm", function (e) { //鼠标点击下拉列表后的事件
    var _value = e.item.value;
    myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
    G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
    setPlace();
});

function setPlace() {
    map.clearOverlays(); //清除地图上所有覆盖物
    function myFun() {
        var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
        map.centerAndZoom(pp, 17);
        var marker = new BMap.Marker(pp)
        map.addOverlay(marker); //添加标注
        //添加双击事件
        marker.addEventListener("dblclick", attribute);
    }

    var local = new BMap.LocalSearch(map, { //智能搜索
        onSearchComplete: myFun
    });
    local.search(myValue);
}

//获取覆盖物位置
function attribute(e) {
    var p = e.target.getPosition();
    setPoint(p);
    setPointSpan(p);
}

